
# MySQL my.cnf tuning
# copied from: https://github.com/joyent/mi-percona/blob/master/copy/var/zoneinit/includes/31-mysql.sh

IP_INTERNAL=$(mdata-get sdc:nics | /usr/bin/json -ag ip -c 'this.interface === "net0"' 2>/dev/null);
# Workaround for using DHCP so IP_INTERNAL or IP_EXTERNAL is empty
if [[ -z "${IP_INTERNAL}" ]]; then
  IP_INTERNAL="0.0.0.0"
fi
MEMCAP=$(kstat -c zone_memory_cap -s physcap -p | cut -f2 | awk '{ printf "%d", $1/1024/1024 }');

# innodb_buffer_pool_size
INNODB_BUFFER_POOL_SIZE=$(echo -e "scale=0; ${MEMCAP}/2"|bc)M

# back_log
BACK_LOG=64
[[ ${MEMCAP} -gt 8000 ]] && BACK_LOG=128

# max_connections
[[ ${MEMCAP} -lt 1000 ]] && MAX_CONNECTIONS=200
[[ ${MEMCAP} -gt 1000 ]] && MAX_CONNECTIONS=500
[[ ${MEMCAP} -gt 2000 ]] && MAX_CONNECTIONS=1000
#[[ ${MEMCAP} -gt 3000 ]] && MAX_CONNECTIONS=2000
#[[ ${MEMCAP} -gt 5000 ]] && MAX_CONNECTIONS=5000

# thread_cache_size
THREAD_CACHE_SIZE=$((${MAX_CONNECTIONS}/2))
[[ ${THREAD_CACHE_SIZE} -gt 1000 ]] && THREAD_CACHE_SIZE=1000

log "tuning MySQL configuration"
gsed -i \
        -e "s/bind-address = 127.0.0.1/bind-address = ${IP_INTERNAL}/" \
        -e "s/back_log = 64/back_log = ${BACK_LOG}/" \
        -e "s/thread_cache_size = 1000/thread_cache_size = ${THREAD_CACHE_SIZE}/" \
        -e "s/max_connections = 1000/max_connections = ${MAX_CONNECTIONS}/" \
        -e "s/net_buffer_length = 2K/net_buffer_length = 16384/" \
        -e "s/innodb_buffer_pool_size = [0-9]*M/innodb_buffer_pool_size = ${INNODB_BUFFER_POOL_SIZE}/" \
        tmp/my.cnf